<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible"  style="width: 80%; ">
    <el-form style="height:550px;overflow-y: auto;overflow-x: hidden;"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-divider content-position="left">应收款信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="24" v-if="showSelect">
<!--          <el-form-item label="应收款信息" >-->
<!--            {{formData.contractMsg}}-->
<!--          </el-form-item>-->
          <el-form-item label="合同名称" prop="contractId">
            <!--            <el-input v-model="formData.contractName" placeholder="请输入合同名称"/>-->
            <el-select
              v-model="formData.contractReceiveRecordId"
              filterable
              placeholder="请选择合同名称"
              style="width: 100%"
              @change="setContract"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.contractArchiveInfo.contractName+'【'+ item.contractCode+'】'+'期数：('+item.instalmentCount+'）'+item.serviceTerm"
                :value="item.id"
                :disabled="item.disabledInvoice"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24" v-if="!showSelect">
          <el-form-item label="合同名称" >
            <el-input disabled v-model="formData.contractName" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="合同编号" >
            <el-input disabled v-model="formData.contractCode" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同服务期">
            <el-date-picker disabled
              v-model="formData.contractStartTime"
              type="date"
              value-format="x"
              placeholder=""
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同总额" >
            <el-input disabled v-model="formData.contractPriceNumber" placeholder="" ><template #append>元(小写)</template></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="期数" >
            <el-input disabled v-model="formData.instalmentCount" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应收时间">
            <el-date-picker disabled
              v-model="formData.receiveDate"
              type="date"
              value-format="x"
              placeholder=""
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="应收金额">
            <el-input disabled v-model="formData.receiveMoney" placeholder="" ><template #append>元(小写)</template></el-input>
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="已收金额">-->
<!--            <el-input disabled v-model="contractData.contractPriceNumber" placeholder="" ><template #append>元(小写)</template></el-input>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
      </el-row>
<!--      <el-row :gutter="20">-->
<!--        <el-col :span="24">-->
<!--          <el-form-item label="备注" prop="contractCode">-->
<!--            <el-input disabled v-model="contractData.contractPriceNumber" placeholder="" ><template #append>元(小写)</template></el-input>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="已收金额" prop="contractPriceNumber">-->
<!--            <el-input disabled v-model="contractData.contractPriceNumber" placeholder="" ><template #append>元(小写)</template></el-input>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->
      <el-divider content-position="left">开票资料</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="公司信息" prop="companyId">
            <el-select filterable  @change="setBankOption()" v-model="formData.companyId" placeholder="请选择公司信息">
              <el-option
                v-for="dict in sellerBankOptions"
                :key="dict.id"
                :label="dict.companyName+ '，纳税人识别号：'+ dict.taxNumber+ '，开户银行：'+ dict.bankName+ '，银行账户：'+ dict.bankAccount"
                :value="dict.id"

              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入发票名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  label-width="200px" label="社会信用代码/纳税人识别号" prop="taxIdNumber">
            <el-input v-model="formData.taxIdNumber" placeholder="请输入社会信用代码/纳税人识别号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户银行" prop="bankName">
            <el-input v-model="formData.bankName" placeholder="请输入开户银行" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开户账号" prop="bankAccount">
            <el-input v-model="formData.bankAccount" placeholder="请输入开户账号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">发票信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票号码" prop="invoiceNumber">
            <el-input v-model="formData.invoiceNumber" placeholder="请输入发票号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票日期" prop="invoiceDate">
            <el-date-picker style="width:100%"
              v-model="formData.invoiceDate"
              type="date"
              value-format="x"
              placeholder="选择开票日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="票种" prop="invoiceType">
            <el-select v-model="formData.invoiceType" placeholder="请选择票种">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_INVOICE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="特定业务" prop="specificBusiness">
            <el-select v-model="formData.specificBusiness" placeholder="请选择特定业务">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.BIZ_INVOICE_BIZ)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票金额" prop="invoiceAmount">
            <el-input  @change="calcTax"  type="number"  :min="0" :max="formData.receiveMoney"
                       step="0.01" v-model="formData.invoiceAmount" placeholder="请输入发票金额" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税率" prop="taxRate">
            <el-select @change="calcTax" v-model="formData.taxRate" placeholder="请选择税率">
              <el-option
                v-for="dict in getDictOptions(DICT_TYPE.BIZ_INVOICE_TAX)"
                :key="dict.value"
                :label="dict.label+'%'"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="税金" prop="taxAmount">
            <el-input disabled v-model="formData.taxAmount" placeholder="请输入税金" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="不含税金额" prop="amountWithoutTax">
            <el-input disabled v-model="formData.amountWithoutTax" placeholder="请输入不含税金额" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="formData.remarks" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销方银行" prop="sellerBank">
            <el-select v-model="formData.sellerBank" placeholder="请选择销方银行">
              <el-option
                v-for="dict in sellerBankOptions2"
                :key="dict.id"
                :label="dict.bankName+ '：'+ dict.bankAccount"
                :value="dict.bankName+ '：'+ dict.bankAccount"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择发票状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_INVOICE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签收人" prop="signName">
            <el-input v-model="formData.signName" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="云开票状态" prop="cloudStatus">
            <el-input v-model="formData.cloudStatus" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.status == '作废'">
          <el-form-item label="作废时间" prop="cancelTime">
            <el-date-picker
              v-model="formData.cancelTime"
              type="date"
              value-format="x"
              placeholder="选择作废时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">开票内容</el-divider>
      <!-- 子表的表单 -->
      <ItemForm ref="itemFormRef" :invoice-id="formData.id" />

<!--      <el-form-item label="更新时间" prop="updatedAt">-->
<!--        <el-date-picker-->
<!--          v-model="formData.updatedAt"-->
<!--          type="date"-->
<!--          value-format="x"-->
<!--          placeholder="选择更新时间"-->
<!--        />-->
<!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" v-if="!view" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE,getDictOptions } from '@/utils/dict'
import { BizInvoiceManagementApi, BizInvoiceManagement } from '@/api/biz/invoice'
import ItemForm from './components/ItemForm.vue'
import {ContractArchiveApi} from "@/api/biz/contract";
import {CompanyInfoApi} from "@/api/biz/company";
import {ContractArchiveReceiveRecordApi} from "@/api/biz/receivables";
import {formatTime} from "@/utils";
const itemFormRef = ref()
// 监听输入变化
// watch(taxInclusive, (newValue) => {
//   if (newValue && !isNaN(parseFloat(newValue))) {
//     taxExclusive.value = '';
//   }
// });



/** 发票管理 表单 */
defineOptions({ name: 'BizInvoiceManagementForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const calcTax =  async () => {
  formData.value.taxAmount = (parseFloat(formData.value.invoiceAmount)/ ( (1 + parseFloat(formData.value.taxRate) / 100)) * (parseFloat(formData.value.taxRate) / 100)).toFixed(2)
  formData.value.amountWithoutTax = (parseFloat(formData.value.invoiceAmount) - parseFloat(formData.value.taxAmount)).toFixed(2)
}
const contractData = ref({
  id: undefined,
  contractType: undefined,
  isTest: undefined,
  contractName: undefined,
  contractCode: undefined,
  customerId: undefined,
  customerName: undefined,
  signTime: undefined,
  powerAccountId: undefined,
  powerAccount: undefined,
  projectCode: undefined,
  customerDirectorName: undefined,
  contactNumber: undefined,
  companyDirectorName: undefined,
  manageUnitId: undefined,
  manageUnitName: undefined,
  costomerManager: undefined,
  powerLocation: undefined,
  powerAddress: undefined,
  powerArea: undefined,
  serviceContent: undefined,
  supplement: undefined,
  transformerAmount: undefined,
  totalVolume: undefined,
  measureAmount: undefined,
  contractStartTime: undefined,
  contractEndTime: undefined,
  contractMonthNumber: undefined,
  contractMonthText: undefined,
  feePerMontNumber: undefined,
  feePerMontText: undefined,
  factFeePerMonthNumber: undefined,
  factFeePerMonthText: undefined,
  contractPriceNumber: undefined,
  contractPriceText: undefined,
  firstPay: undefined,
  firstPayDate: undefined,
  instalmentCount: undefined,
  receiveInterval: undefined,
  intervalPay: undefined,
  serviceUnitId: undefined,
  serviceUnitName: undefined,
  serviceManagerName: undefined,
  introducer: undefined,
  introduceChannel: undefined,
  remark: undefined,
  attachmentUrl: undefined,
  ownerUserId: undefined,
  transformerList: [],
  receiveRecordList: [],
  // contractArchiveInfo: {
  //   contractName: undefined,
  // },
  status: undefined
})
const formData = ref({
  id: undefined,
  contractCode: undefined,
  name: undefined,
  taxIdNumber: undefined,
  contactPhone: undefined,
  bankName: undefined,
  bankAccount: undefined,
  address: undefined,
  invoiceNumber: undefined,
  invoiceDate: new Date().getTime(), // formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
  invoiceType: '数电专票',
  specificBusiness: '普通开具',
  invoiceAmount: undefined,
  taxRate: undefined,
  taxAmount: undefined,
  amountWithoutTax: undefined,
  remarks: undefined,
  sellerBank: undefined,
  updatedAt: undefined,
})

const checkInvoiceAmount = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('发票金额不能为空'))
  }
  // setTimeout(() => {
  // console.info(parseFloat(value))
  // console.info( /^-?\d*\.\d+$/.test(value) || /^-?\d*$/.test(value))
  // console.info(Float.isInteger(parseFloat(value)))
  if (!( /^-?\d*\.\d+$/.test(value) || /^-?\d*$/.test(value))) {
    callback(new Error('请输入正确的发票金额'))
  } else {
    if (parseFloat(value) > parseFloat(formData.value.receiveMoney)) {
      callback(new Error('发票金额不能大于应收金额'))
    } else {
      callback()
    }
  }
  // }, 1000)
}

const formRules = reactive({
  contractCode: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  taxIdNumber: [{ required: true, message: '社会信用代码/纳税人识别号不能为空', trigger: 'blur' }],
  invoiceType: [{ required: true, message: '票种不能为空', trigger: 'change' }],
  specificBusiness: [{ required: true, message: '特定业务不能为空', trigger: 'blur' }],
  // invoiceAmount: [{ required: true, message: '发票金额不能为空', trigger: 'blur' }],
  invoiceAmount: [{required: true,  validator: checkInvoiceAmount, trigger: 'blur' }],
  taxRate: [{ required: true, message: '税率不能为空', trigger: 'change' }],
  taxAmount: [{ required: true, message: '税金不能为空', trigger: 'blur' }],
  amountWithoutTax: [{ required: true, message: '不含税金额不能为空', trigger: 'blur' }],
})

const formRef = ref() // 表单 Ref
const sellerBankOptions = ref([])
const sellerBankOptions2 = ref([])
// 返回对象数组中付款金额的总和
const sumPayments = (arr) => arr.reduce((sum, item) => sum + (item.payMoney || 0), 0);
const payMoney = ref(0) // 已付金额
const options = ref([])
let showSelect = reactive(true)

function setBankOption() {
  sellerBankOptions.value.forEach(a => {
    if ((a.id) === formData.value.companyId) {
       formData.value.name= a.companyName
        formData.value.address= a.address
        formData.value.bankAccount= a.bankAccount
        formData.value.bankName= a.bankName
        formData.value.contactPhone= a.phone
        formData.value.taxIdNumber= a.taxNumber
    }
  })
}

function setContract(){
  options.value.forEach(a => {
    if ((a.id) === formData.value.contractReceiveRecordId) {
      formData.value.contractName = a.contractArchiveInfo.contractName
      formData.value.contractCode = a.contractArchiveInfo.contractCode
      formData.value.contractReceiveRecordId = a.id
      formData.value.contractPriceNumber = a.contractArchiveInfo.contractPriceNumber
      formData.value.contractStartTime = a.contractArchiveInfo.contractStartTime
      formData.value.instalmentCount = a.instalmentCount
      formData.value.receiveMoney = a.receiveMoney
      formData.value.receiveDate = a.receiveDate
      payMoney.value = sumPayments(a.payment)

      customerId.value = a.contractArchiveInfo.customerId
      getCompanyInfo()
    }
  })
}
const getCompanyInfo = async () => {
  const data = await CompanyInfoApi.getCompanyInfoList({customerId: customerId.value,type: '1'})
  sellerBankOptions.value = data
}


function isEmptyObject(obj: object): boolean {
  return Object.keys(obj).length === 0;
}

const view  = ref(false)
const customerId = ref(null)
/** 打开弹窗 */
const open = async (type: string, id?: number, contract?: object) => {
  if(type == 'view'){
    view.value = true
    type = 'update'
  } else {
    view.value = false
  }
  formLoading.value = true
  dialogVisible.value = true
  options.value = await ContractArchiveReceiveRecordApi.getContractArchiveReceiveRecordList()
  const data = await CompanyInfoApi.getCompanyInfoList({type: '2'})
  sellerBankOptions2.value = data
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    // formLoading.value = true
    try {
      formData.value = await BizInvoiceManagementApi.getBizInvoiceManagement(id)
      customerId.value = formData.value.customerId
      await getCompanyInfo()
    } finally {
      formLoading.value = false
    }
  }
  // console.info(!isEmptyObject(contract))
  if(!isEmptyObject(contract)) {
    showSelect = false
    contractData.value = contract
    formData.value.contractCode = contractData.value.contractArchiveInfo.contractCode
    formData.value.contractName = contractData.value.contractArchiveInfo.contractName
    formData.value.contractReceiveRecordId = contractData.value.id
    formData.value.contractPriceNumber = contractData.value.contractArchiveInfo.contractPriceNumber
    formData.value.contractStartTime = contractData.value.contractArchiveInfo.contractStartTime
    formData.value.instalmentCount = contractData.value.instalmentCount
    formData.value.receiveMoney = contractData.value.receiveMoney
    formData.value.receiveDate = contractData.value.receiveDate
    customerId.value = contractData.value.contractArchiveInfo.customerId
    await getCompanyInfo()
  }
  formLoading.value = false
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BizInvoiceManagement
    // 拼接子表的数据
    data.items = itemFormRef.value.getData()
    if (formType.value === 'create') {
      await BizInvoiceManagementApi.createBizInvoiceManagement(data)
      message.success(t('common.createSuccess'))
    } else {
      await BizInvoiceManagementApi.updateBizInvoiceManagement(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractCode: undefined,
    name: undefined,
    taxIdNumber: undefined,
    contactPhone: undefined,
    bankName: undefined,
    bankAccount: undefined,
    address: undefined,
    invoiceNumber: undefined,
    invoiceDate: new Date().getTime(), // formatTime(new Date(), 'yyyy-MM-dd HH:mm:ss'),
    invoiceType: '数电专票',
    specificBusiness: '普通开具',
    invoiceAmount: undefined,
    taxRate: undefined,
    taxAmount: undefined,
    amountWithoutTax: undefined,
    remarks: undefined,
    sellerBank: undefined,
    updatedAt: undefined,
    signName: undefined,
    status: '生效',
    cloudStatus: undefined,
    cancelTime: undefined,
  }
  formRef.value?.resetFields()
}
</script>
